package cn.easier.activity.console.repository;

import cn.easier.activity.web.entity.ActivityCouponCode;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 券码 Repository
 */
@Repository
public interface ActivityCouponCodeRepository extends JpaRepository<ActivityCouponCode, Integer> {

    /**
     * 查找奖品券码
     *
     * @param activityPrizeId 奖品id
     */
    List<ActivityCouponCode> findActivityCouponCodesByActivityPrizeId(Integer activityPrizeId);


    /**
     * 查找奖品券码使用情况
     *
     * @param activityPrizeId 奖品id
     * @param available 是否有效
     */
    @Query(value = "select count(1) FROM `activity_coupon_code` WHERE activity_prize_id = ? AND is_available IS ?", nativeQuery = true)
    int countByAvailable(Integer activityPrizeId, Boolean available);

    /**
     * 删除指定券码
     */
    @Query(value = "DELETE FROM `activity_coupon_code` WHERE id = ? AND USER = ? AND is_available IS TRUE", nativeQuery = true)
    @Modifying
    int deleteFlag(Integer id, String user);

    /**
     * 删除指定券码
     */
    @Query(value = "DELETE FROM `activity_coupon_code` WHERE id = ? AND is_available IS TRUE", nativeQuery = true)
    @Modifying
    int deleteByFlag(Integer id);

    /**
     * 批量删除（数据库name字段存储的版本号）
     * @param name 版本号
     */
    @Query(value = "DELETE FROM `activity_coupon_code` WHERE NAME = ? AND USER = ? AND is_available IS TRUE", nativeQuery = true)
    @Modifying
    int deleteByBatch(String name, String user);

    ActivityCouponCode findByIdAndUser(Integer id, String user);
}
